package com.pro01.backend.controller;

import com.pro01.backend.dto.ActiveTorrentDTO;
import com.pro01.backend.dto.TorrentWithConnectionDTO;
import com.pro01.backend.pojo.PageResult;
import com.pro01.backend.pojo.Result;
import com.pro01.backend.pojo.TorrentClass;
import com.pro01.backend.pojo.TorrentDownload;
import com.pro01.backend.service.TorrentService;
import com.pro01.backend.utils.JwtUtil;
import com.pro01.backend.utils.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/torrents")
public class TorrentController {

    @Autowired
    private TorrentService torrentService;
//111
    // 上传种子
    @PostMapping("/upload")
    public Result<?> uploadTorrent(HttpServletRequest request,
                                   @RequestParam("name") String name,
                                   @RequestParam("category") String category,
                                   @RequestParam("file") MultipartFile file) {
        try {
//            String token = request.getHeader("Authorization");
//            Map<String, Object> claims = JwtUtil.parseToken(token);
//            if (claims == null) {
//                return Result.error("未授权，请先登录");
//            }
//
//            Long userId = ((Number) claims.get("id")).longValue();
            Long userId = TokenUtil.getUserId(request);

            boolean success = torrentService.uploadTorrent(userId, name, category, file);
            return success ? Result.success("种子上传成功") : Result.error("种子上传失败");
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }

    // 获取所有种子
//    @GetMapping
//    public Result<List<TorrentClass>> getAllTorrents() {
//        return Result.success(torrentService.getAllTorrents());
//    }
    @GetMapping
    public Result<PageResult<TorrentClass>> getAllTorrents(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            HttpServletRequest request) {

        // 登录验证：无效 token 会抛异常
        Long userId = TokenUtil.getUserId(request);

        PageResult<TorrentClass> result = torrentService.getAllTorrentsPaged(pageNum, pageSize);
        return Result.success(result);
    }



    // 获取某个分类的种子
//    @GetMapping("/category/{category}")
//    public Result<List<TorrentClass>> getTorrentsByCategory(@PathVariable String category) {
//        return Result.success(torrentService.getTorrentsByCategory(category));
//    }
    @GetMapping("/category/{category}")
    public Result<PageResult<TorrentClass>> getTorrentsByCategory(
            @PathVariable String category,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            HttpServletRequest request) {

        // 添加登录校验：无效 token 会抛异常
        Long userId = TokenUtil.getUserId(request);

        PageResult<TorrentClass> result = torrentService.getTorrentsByCategoryPaged(category, pageNum, pageSize);
        return Result.success(result);
    }


    // 🔍 搜索种子接口
    @GetMapping("/search")
    public Result<PageResult<TorrentClass>> searchTorrents(@RequestParam("keyword") String keyword,
                                                           @RequestParam(defaultValue = "1") int pageNum,
                                                           @RequestParam(defaultValue = "10") int pageSize,
                                                           HttpServletRequest request) {
        try {
            // 登录校验
            Long userId = TokenUtil.getUserId(request);

            // 防止 pageSize 太大
            if (pageSize > 50) {
                pageSize = 50;
            }

            PageResult<TorrentClass> result = torrentService.searchTorrentsByKeyword(keyword, pageNum, pageSize);
            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("搜索失败：" + e.getMessage());
        }
    }


    @GetMapping("/my-uploads")
    public Result<PageResult<TorrentClass>> getMyUploadedTorrents(HttpServletRequest request,
                                                                  @RequestParam(defaultValue = "1") int pageNum,
                                                                  @RequestParam(defaultValue = "10") int pageSize) {
        try {
            // 校验登录
//            String token = request.getHeader("Authorization");
//            Map<String, Object> claims = JwtUtil.parseToken(token);
//            if (claims == null) {
//                return Result.error("未登录，请先登录！");
//            }
//
//            Long userId = ((Number) claims.get("id")).longValue();

            Long userId = TokenUtil.getUserId(request);

            if (pageSize > 50) {
                pageSize = 50;
            }

            PageResult<TorrentClass> result = torrentService.getUserUploadedTorrents(userId, pageNum, pageSize);
            return Result.success(result);

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败：" + e.getMessage());
        }
    }

//    @GetMapping("/my-downloads")
//    public Result<PageResult<Map<String, Object>>> getMyDownloads(HttpServletRequest request,
//                                                                  @RequestParam(defaultValue = "1") int pageNum,
//                                                                  @RequestParam(defaultValue = "10") int pageSize) {
//        try {
////            String token = request.getHeader("Authorization");
////            Map<String, Object> claims = JwtUtil.parseToken(token);
////            if (claims == null) {
////                return Result.error("未登录，请先登录！");
////            }
////            Long userId = ((Number) claims.get("id")).longValue();
//
//            Long userId = TokenUtil.getUserId(request);
//
//            if (pageSize > 50) {
//                pageSize = 50;
//            }
//
//            PageResult<Map<String, Object>> result = torrentService.getUserDownloadRecords(userId, pageNum, pageSize);
//            return Result.success(result);
//
//        } catch (Exception e) {
//            e.printStackTrace();
//            return Result.error("查询失败：" + e.getMessage());
//        }
//    }
@GetMapping("/my-downloads")
public Result<PageResult<TorrentDownload>> getMyDownloads(HttpServletRequest request,
                                                          @RequestParam(defaultValue = "1") int pageNum,
                                                          @RequestParam(defaultValue = "10") int pageSize) {
    try {
        Long userId = TokenUtil.getUserId(request);

        if (pageSize > 50) {
            pageSize = 50;
        }

        PageResult<TorrentDownload> result = torrentService.getUserDownloadRecords(userId, pageNum, pageSize);
        return Result.success(result);

    } catch (Exception e) {
        e.printStackTrace();
        return Result.error("查询失败：" + e.getMessage());
    }
}

    // 获取种子详情
    @GetMapping("/{torrentId}")
    public Result<TorrentClass> getTorrentById(@PathVariable Long torrentId, HttpServletRequest request) {
        // 添加登录校验
        Long userId = TokenUtil.getUserId(request);

        TorrentClass torrent = torrentService.getTorrentById(torrentId);
        return torrent != null ? Result.success(torrent) : Result.error("种子不存在");
    }


    // 删除种子（仅 ADMIN）
//    @DeleteMapping("/{id}")
//    public Result<Void> deleteTorrent(HttpServletRequest request, @PathVariable Long id) {
//        String token = request.getHeader("Authorization");
//        Map<String, Object> claims = JwtUtil.parseToken(token);
//        if (claims == null || !"ADMIN".equals(claims.get("role"))) {
//            return Result.error("无权限操作");
//        }
//
//        return torrentService.deleteTorrent(id) ? Result.success() : Result.error("删除种子失败");
//    }

    @GetMapping("/download/{torrentId}")
    public void downloadTorrent(@PathVariable Long torrentId,
                                HttpServletRequest request,
                                HttpServletResponse response) {
        try {
            // 从请求头获取 JWT 并解析 userId
//            String token = request.getHeader("Authorization");
//            Map<String, Object> claims = JwtUtil.parseToken(token);
//            if (claims == null) {
//                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "未授权，请先登录");
//                return;
//            }
//
//            Long userId = ((Number) claims.get("id")).longValue();

            Long userId = TokenUtil.getUserId(request);

            // 调用 Service 获取注入了 peer_id 的 .torrent 文件
            File modifiedTorrent = torrentService.downloadTorrent(userId, torrentId);

            // 设置响应类型为 BitTorrent 文件类型
            response.setContentType("application/x-bittorrent");
            response.setHeader("Content-Disposition", "attachment; filename=" + modifiedTorrent.getName());

            // 把文件写入响应体
            java.nio.file.Files.copy(modifiedTorrent.toPath(), response.getOutputStream());
            response.flushBuffer();

        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "下载失败：" + e.getMessage());
            } catch (IOException ignored) {}
        }
    }

    @GetMapping("/download-with-passkey/{torrentId}")
    public void downloadTorrentWithPasskey(@PathVariable Long torrentId,
                                           HttpServletRequest request,
                                           HttpServletResponse response) {
        try {
            Long userId = TokenUtil.getUserId(request);

            // 调用 service 获取注入 passkey 的 .torrent 文件
            File modifiedTorrent = torrentService.downloadTorrentWithPasskey(userId, torrentId);

            response.setContentType("application/x-bittorrent");
            response.setHeader("Content-Disposition", "attachment; filename=" + modifiedTorrent.getName());

            java.nio.file.Files.copy(modifiedTorrent.toPath(), response.getOutputStream());
            response.flushBuffer();

        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "下载失败：" + e.getMessage());
            } catch (IOException ignored) {}
        }
    }

    // 查询当前有效促销种子
    @GetMapping("/promotion/active")
    public Result<PageResult<Map<String, Object>>> getActivePromotions(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            HttpServletRequest request) {
        try {
            // 🛡️ 检查 JWT 是否有效
//            String token = request.getHeader("Authorization");
//            Map<String, Object> claims = JwtUtil.parseToken(token);
//            if (claims == null) {
//                return Result.error("未登录，请先登录！");
//            }
            Long userId = TokenUtil.getUserId(request);
            PageResult<Map<String, Object>> result = torrentService.getActivePromotions(pageNum, pageSize);
            return Result.success(result);

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取促销种子失败：" + e.getMessage());
        }
    }

    // 连接性检测
    @GetMapping("/active")
    public Result<PageResult<ActiveTorrentDTO>> getActiveTorrents(@RequestParam(defaultValue = "1") int pageNum,
                                                                  @RequestParam(defaultValue = "10") int pageSize) {
        PageResult<ActiveTorrentDTO> result = torrentService.getActiveTorrents(pageNum, pageSize);
        return Result.success(result);
    }

    // 种子连接性检测
    @GetMapping("/active-status")
    public Result<PageResult<TorrentWithConnectionDTO>> getTorrentsWithConnection(@RequestParam(defaultValue = "1") int pageNum,
                                                                                  @RequestParam(defaultValue = "10") int pageSize) {
        PageResult<TorrentWithConnectionDTO> result = torrentService.getAllTorrentsWithConnection(pageNum, pageSize);
        return Result.success(result);
    }

}
